var scene, camera, renderer;
var controls;
var allTexture,
  objMap = {};
var ASSETSURL = "../assets/01/"; // 资源主目录路径
var sceneId = 2;
var btns = document.querySelectorAll("button");
addActiveStyle();

// 初始化
function init() {
  scene = new THREE.Scene();
  createCamera();

  renderer = new THREE.WebGLRenderer({
    antialias: true,
  });
  renderer.setSize(document.body.clientWidth, document.body.clientHeight);
  document.getElementById("container").appendChild(renderer.domElement);

  controls = new THREE.OrbitControls(camera, renderer.domElement);
  
  loadAudio();

  loadAllTexture(function(){
    loadModel();
    addBtnsEventListener();
  });

  //   addLight();

  loop();
}

// 创建相机
function createCamera(){
  camera = new THREE.PerspectiveCamera(
    90,
    document.body.clientWidth / document.body.clientHeight,
    0.1,
    1000
  );
  camera.position.set(0, 1.5, 4);
}

// 批量加载所需纹理集
function loadAllTexture(cb) {
  allTexture = {};
  var loadIndex = 0;
  var textures = [];
  var _data = {
    1: ["RSE_mat_baseColor", "RSE_misc_baseColor", "RSE_pokeball_baseColor"],
    2: ["fireRed_material_baseColor"],
    3: ["fireRed_loreleiRoom_baseColor", "fireRed_loreleiRoom_misc_baseColor"],
  };
  for (var key in _data) {
    var _list = _data[key];
    _list.forEach(function (item) {
      textures.push({
        group: key,
        name: item,
      });
    });
  }
  function loadNextTexture() {
    var textureObj = textures[loadIndex];
    loadTexture(
      ASSETSURL + textureObj.group + "/textures/" + textureObj.name + ".png",
      function (texture) {
        allTexture[textureObj.name] = {
          texture: texture,
        };
        if (loadIndex < textures.length - 1) {
          loadIndex++;
          loadNextTexture();
        } else {
          if (cb) cb();
        }
      }
    );
  }
  loadNextTexture();
}

// 加载纹理
function loadTexture(filepath, cb) {
  var textureLoader = new THREE.TextureLoader();
  textureLoader.load(filepath, cb);
}

// 加载模型
function loadModel(cb) {
  if(objMap[sceneId]){
    scene.add(objMap[sceneId].parent);
    cb && cb();
    return
  }
  var loader = new THREE.GLTFLoader();
  loader.load(ASSETSURL + sceneId + "/scene.gltf", function (gltf) {
    scene.add(gltf.scene);
    objMap[sceneId] = gltf.scene.children[0];
    cb && cb();
  });
}

// 添加灯光
function addLight() {
  var ambientLight = new THREE.AmbientLight(0xd5d5d5);
  ambientLight.intensity = 1.2;
  scene.add(ambientLight);

  var bottomRightDirLight = new THREE.DirectionalLight();
  bottomRightDirLight.position.x = 5;
  bottomRightDirLight.position.y = 3;
  bottomRightDirLight.position.z = -5;
  bottomRightDirLight.intensity = 0.8;

  var helper = new THREE.DirectionalLightHelper(bottomRightDirLight, 1);
  scene.add(helper);
  scene.add(bottomRightDirLight);

  var frontDirLight = new THREE.DirectionalLight(0xffffff);

  frontDirLight.position.x = -5;
  frontDirLight.position.y = 3;
  frontDirLight.position.z = 5;
  frontDirLight.intensity = 0.8;
  //directionalLight.castShadow=true;

  var helper = new THREE.DirectionalLightHelper(frontDirLight, 1);
  scene.add(helper);
  scene.add(frontDirLight);
}

// 主循环
function loop() {
  requestAnimationFrame(loop);
  renderer.render(scene, camera);
}

window.onload = init;



function addBtnsEventListener(){
  btns.forEach(function (btn) {
    btn.addEventListener("click", onClickEvent);
  });
}



function addActiveStyle(){
  btns.forEach(function(btn){
    if(btn.dataset.id==sceneId){
      btn.classList.add("active")
    }else{
      btn.classList.remove("active");
    }
  })
}

function clearAllModel(){
  scene.children.length = 0;
}

function onClickEvent(e){
  var id = e.target.dataset.id || 1;
  if(sceneId == id) return;
  sceneId = id;
  addActiveStyle();
  clearAllModel();
  loadAudio();
  loadModel(function(){
    camera.position.set(0, 1.5, 4);
    controls = new THREE.OrbitControls(camera, renderer.domElement);
  });
}

function loadAudio(){
  var audio = document.getElementById("audio");
  audio.src = ASSETSURL + sceneId + "/bgm.mp3";
  audio.play()
  return audio;
}